#ifndef GW_MODPROTOCOL_H
#define GW_MODPROTOCOL_H
#include "GW_Protocol.h"
#include "GWType.h"

#define MAXREGISTER	128
#define	LEN_INPUTQUEST	6

#define MODBUS_IOREG 0x03
#define MODBUS_INPUTREG 0x04
#define MODBUS_WRITEHOLD   0x10
#define MODBUS_IOCTL 0x05
#define MODBUS_GETVALUE 0x02
#define MODBUS_GETOPT   0x01

#define  PROTOCOL_CIR   0
#define  PROTOCOL_MODBUS   1
#define  PROTOCOL_GW    2

#define	DIR_REQUEST	0
#define DIR_REPONSE	1

#pragma pack(1)
typedef union
{
   struct
   {
      u32 data;
   } _Interget;
   u8 Interget_Buf[sizeof(_Interget)];
} GW_Data_Interget;

typedef union
{
   struct
   {
      u16 data;
   } _HalfInterget;
   u8 HalfInterget_Buf[sizeof(_HalfInterget)];
} GW_Data_HalfInterget;

typedef struct modRequestFrame
{
   volatile u8    Addr;
   volatile u8    Cmd;
   volatile u16   Register;
   volatile u16   Length;
   volatile u16   crc;
};

typedef struct modResponseFrame
{
   volatile u8    Addr;
   volatile u8    Cmd;
   volatile u8    Length;
   volatile u16   dat[MAXREGISTER];
   volatile u16   crc;
};

#pragma pack()

class GW_ModProtocol : public GW_Protocol
{
public:
   GW_ModProtocol();
   void  Init();
   bool  Matching(int length, u8 *data, u8 id, int direction);
   bool  Recved(u8 *responseDat, int length, u8 id);
   bool  Poll(int ch, int mode, int regcnt);
   bool  SignalCoilWrite(int ch, bool on);
   bool  DataLoaded(u8 *responseDat, int length, int mode);
   bool  GetWaiting();
   bool  isVaild();
   //void SendMsg();
   u8    GetFunctionID();
   u16   GetRequestData();
   u8*   GetSendMsg(int *len);
   u16   GetStartReg();
   u16   GetEffectRegCnt();
   bool waiting;
   u8   sendLength;
   int   mode;
   //void GetByte(u8 dat);

private:
   u16   startReg;
   u16   effectRegCnt;
   modRequestFrame BReq;
   modResponseFrame BRes;
   static const int MAXSENDBUF = 128;
   //u8 sendbuf[MAXSENDBUF];

   //modResponseFrame BRes;


protected:
   void beforeTimeout();
   void afterTimeout();
   void beforeGetByte();
   void afterGetByte();
};
//const int GW_ModProtocol::MAXBUF = 20;

#define MODBUS_IOREG 0x03
#define MODBUS_INPUTREG 0x04
#define MODBUS_WRITEHOLD   0x10
#define MODBUS_WRITESIGCOIL  0x05
#define MODBUS_IOCTL 0x05
#define MODBUS_GETVALUE 0x02
#define MODBUS_GETOPT   0x01

#define ADDR_Value   0x0002
#define ADDR_UniqeID 0x0010
#define ADDR_OPT     0x0008

#define	MODBUS_BB	0x01
#define  MODBUS_GW	0x02
#define  MODBUS_MB   0x03

#endif
